



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#FFF">
  <link rel="apple-touch-icon" sizes="180x180" href="/lostyu/images/apple-touch-icon.png">

<link rel="icon" type="image/ico" sizes="32x32" href="/lostyu/images/favicon.ico">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">


<link rel="alternate" type="application/rss+xml" title="Eden" href="https://luhongdeng.gitee.io/rss.xml" />
<link rel="alternate" type="application/atom+xml" title="Eden" href="https://luhongdeng.gitee.io/atom.xml" />
<link rel="alternate" type="application/json" title="Eden" href="https://luhongdeng.gitee.io/feed.json" />

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Mulish:300,300italic,400,400italic,700,700italic%7CFredericka%20the%20Great:300,300italic,400,400italic,700,700italic%7CNoto%20Serif%20JP:300,300italic,400,400italic,700,700italic%7CNoto%20Serif%20SC:300,300italic,400,400italic,700,700italic%7CInconsolata:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lostyu/css/app.css?v=0.2.5">

  

<link rel="canonical" href="https://luhongdeng.gitee.io/2020/12/23/Java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">



  <title>
Java网络编程 |
我的金子，只给千寻 = Eden</title>
<meta name="generator" content="Hexo 5.3.0"></head>
<body itemscope itemtype="http://schema.org/WebPage">
  <div id="loading">
    <div class="cat">
      <div class="body"></div>
      <div class="head">
        <div class="face"></div>
      </div>
      <div class="foot">
        <div class="tummy-end"></div>
        <div class="bottom"></div>
        <div class="legs left"></div>
        <div class="legs right"></div>
      </div>
      <div class="paw">
        <div class="hands left"></div>
        <div class="hands right"></div>
      </div>
    </div>
  </div>
  <div id="container">
    <header id="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="inner">
        <div id="brand">
          <div class="pjax">
          
  <h1 itemprop="name headline">Java网络编程
  </h1>
  
<div class="meta">
  <span class="item" title="Created: 2020-12-23 23:28:38">
    <span class="icon">
      <i class="ic i-calendar"></i>
    </span>
    <span class="text">Posted on</span>
    <time itemprop="dateCreated datePublished" datetime="2020-12-23T23:28:38+08:00">2020-12-23</time>
  </span>
</div>


          </div>
        </div>
        <nav id="nav">
  <div class="inner">
    <div class="toggle">
      <div class="lines" aria-label="Toggle navigation bar">
        <span class="line"></span>
        <span class="line"></span>
        <span class="line"></span>
      </div>
    </div>
    <ul class="menu">
      <li class="item title"><a href="/lostyu/" rel="start">我的金子，只给千寻</a></li>
    </ul>
    <ul class="right">
      <li class="item theme">
        <i class="ic i-sun"></i>
      </li>
      <li class="item search">
        <i class="ic i-search"></i>
      </li>
    </ul>
  </div>
</nav>

      </div>
      <div id="imgs" class="pjax">
        <ul>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1giclfw2t96j20zk0m8x6p.jpg"></li>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1gicis3attqj20zk0m8k7l.jpg"></li>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1gipesx5fdwj20zk0m81kx.jpg"></li>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1giclhpw3lwj20zk0m8gvw.jpg"></li>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1giph4fomxoj20zk0m8axp.jpg"></li>
          <li class="item" data-background-image="https://tva4.sinaimg.cn/large/6833939bly1giph47e9vtj20zk0m8x6l.jpg"></li>
        </ul>
      </div>
    </header>
    <div id="waves">
      <svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
        <defs>
          <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
        </defs>
        <g class="parallax">
          <use xlink:href="#gentle-wave" x="48" y="0" />
          <use xlink:href="#gentle-wave" x="48" y="3" />
          <use xlink:href="#gentle-wave" x="48" y="5" />
          <use xlink:href="#gentle-wave" x="48" y="7" />
        </g>
      </svg>
    </div>
    <main>
      <div class="inner">
        <div id="main" class="pjax">
          
  <div class="article wrap">
    
<div class="breadcrumb" itemscope itemtype="https://schema.org/BreadcrumbList">
<i class="ic i-home"></i>
<span><a href="/lostyu/">Home</a></span>
</div>

    <article itemscope itemtype="http://schema.org/Article" class="post block" lang="en">
  <link itemprop="mainEntityOfPage" href="https://luhongdeng.gitee.io/2020/12/23/Java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">

  <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="image" content="/lostyu/images/avatar.jpg">
    <meta itemprop="name" content="Eden的个人世界">
    <meta itemprop="description" content=", ">
  </span>

  <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Eden">
  </span>

  <div class="body md" itemprop="articleBody">
    

    <p>网络编程最主要的工作就是在发送端把信息通过规定好的协议进行组装包，在接收端按照规定好的协议把包进行解析，从而提取出对应的信息，达到通信的目的。中间最主要的就是数据包的组装，数据包的过滤，数据包的捕获，数据包的分析，当然最后再做一些处理，代码、开发工具、数据库、服务器架设和网页设计这 5 部分你都要接触。</p>
<h3 id="一-什么是网络编程"><a class="markdownIt-Anchor" href="#一-什么是网络编程">#</a> <strong>一、什么是网络编程</strong></h3>
<ul>
<li>网络编程从大的方面说就是对信息的发送到接收</li>
<li>通过操作相应的 Api 调度计算机硬件资源，并利用传输管道进行数据交换过程</li>
<li>更为具体的涉及：网络模型、套接字、数据包</li>
</ul>
<h4 id="1-7层网络模型-osi"><a class="markdownIt-Anchor" href="#1-7层网络模型-osi">#</a> 1、7 层网络模型 - OSI</h4>
<p><img data-src="1156719-afc57efbe98be4f6.png" alt="img"></p>
<ul>
<li>
<p>应用层：实现多个系统应用进程相互通信，完成一系列业务处理所需的服务。</p>
</li>
<li>
<p>表示层：把应用层提供的信息变换为能够共同理解的形式，提供字符代码、数据格式、控制信息格式、加密等的统一表示。完成一次数据的转换。</p>
</li>
<li>
<p>会话层：应用程序之间建立管理，协调系统和服务之间的交流，，使系统和服务之间有序地进行通信。</p>
</li>
<li>
<p>传输层：将数据进行分割传给网络层并保证数据段的有效性。</p>
</li>
<li>
<p>网络层：控制子网的运行，比如逻辑地址分组以及路由的选择。</p>
</li>
<li>
<p>数据链路层：物理的地址寻找，将原始低处流转换为逻辑的传输路线。</p>
</li>
<li>
<p>物理层：机械的、电子的、定时的原始比特流流传输。电信号或者光信号传输。</p>
<blockquote>
<p>​	基础层：物理层、数据链路层、网络层</p>
<p>​	传输层：TCP-UDP 协议层、Socket</p>
<p>​	高级层：会话层、表示层、应用层</p>
</blockquote>
</li>
</ul>
<h4 id="2-网络模型-对应关系"><a class="markdownIt-Anchor" href="#2-网络模型-对应关系">#</a> 2、网络模型 - 对应关系</h4>
<p><img data-src="image-20201127210126399.png" alt="image-20201127210126399"></p>
<p>TCP/IP 协议毫无疑问是互联网的基础协议，没有它就根本不可能上网，任何和互联网有关的操作都离不开 TCP/IP 协议。</p>
<h4 id="3-socket与tcp-udp"><a class="markdownIt-Anchor" href="#3-socket与tcp-udp">#</a> 3、Socket 与 TCP、UDP</h4>
<ol>
<li>
<p>Socket</p>
<ul>
<li>
<p>简单来说是 IP 地址与端口的结合协议（RFC793)</p>
</li>
<li>
<p>一种地址与端口的结合描述协议</p>
</li>
<li>
<p>TCP/IP 协议的相关 API 的总称；是网络 Api 的集合实现</p>
</li>
<li>
<p>涵盖了：Stream Socket/Datagram Socket</p>
</li>
</ul>
</li>
<li>
<p>Socket 的作用和组成</p>
<ul>
<li>在网络传输中用于唯一标识两个端点之间的链接</li>
<li>端点：包括 IP + Port</li>
<li>4 要素：客户端地址、客户端端口、服务端地址、服务端端口</li>
</ul>
</li>
<li>
<p>Socket 传输原理</p>
<p><img data-src="image-20201127213939228.png" alt="image-20201127213939228"></p>
</li>
<li>
<p>Socket 与 TCP</p>
<ul>
<li>TCP 是面向链接的通信协议</li>
<li>通过三次握手连接，通讯完成时要拆除连接</li>
<li>由于 TCP 是面向连接的所以只能用于端到端的通讯</li>
</ul>
<blockquote>
<p>在 TCP 连接中必须要明确客户端与服务器端，由客户端向服务端发出连接请求，每次连接的创建都需要经过三次握手</p>
</blockquote>
</li>
<li>
<p>Socket 与 UDP</p>
<ul>
<li>UDP 是面向无连接的通讯协议</li>
<li>UDP 数据包括目的端口号和源端口号信息</li>
<li>由于通讯不需要连接，所以可以实现广播发送，并不局限与端到端</li>
</ul>
<blockquote>
<p>简单来说，当一台计算机向另外一台计算机发送数据时，发送端不会确认接收端是否存在，就会发出数据，同样接收端在收到数据时，也不会向发送端反馈是否收到数据。</p>
</blockquote>
<p><img data-src="image-20201127220137112.png" alt="image-20201127220137112"></p>
<p><img data-src="image-20201127220145967.png" alt="image-20201127220145967"></p>
</li>
<li>
<p>Client-Server AppLication CS 模型</p>
<ul>
<li>TCP/IP 协议中，两个进程间通讯的主要模型为：CS 模型</li>
<li>主要目的：协调网络中的计算机资源、服务模式、进程间数据共享</li>
<li>常见的：FTP、SMTP、HTTP</li>
</ul>
</li>
</ol>
<h4 id="4-tcp通信"><a class="markdownIt-Anchor" href="#4-tcp通信">#</a> 4、TCP 通信</h4>
<ol>
<li>
<p>java.net.Socket 类代表一个套接字，并且 java.net.ServerSocket 类为服务器程序提供了一种来监听客户端，并与他们建立连接的机制。</p>
</li>
<li>
<p>两台计算机之间使用套接字建立 TCP 连接过程</p>
<ul>
<li>服务器实例化一个 ServerSocket 对象，表示通过服务器上的端口通信</li>
<li>服务器调用 ServerSocket 类 的 accept（）方法，该方法将一直等待，直到客户端连接到服务器上给定的端口。</li>
<li>服务器正在等待时，一个客户端实例化一个 Socket 对象，指定服务器名称和端口号来请求连接。</li>
<li>Socket 类的构造函数试图将客户端连接到指定的服务器和端口号。如果通信被建立，则在客户端创建一个 Socket 对象能够与服务器进行通信。</li>
<li>在服务器端，accept () 方法返回服务器上一个新的 socket 引用，该 socket 连接到客户端的 socket。</li>
</ul>
</li>
<li>
<p>Socket 类</p>
<p>表示客户端程序的类：  <code>java.net.Socket</code></p>
<blockquote>
<p>构造方法：Socket (String host, int port) ：传递服务器 IP 和端口号<br>
构造方法只要运行，就会和服务器进行连接，连接失败就抛出异常</p>
</blockquote>
<blockquote>
<p>OutputStream getOutputStream () ：返回套接字的输出流，将数据输出，输出到服务器</p>
</blockquote>
<blockquote>
<p>InputStream getInputStream ()  ：返回套接字的输入流，从服务器端读取数据<br>
客户端服务器数据交换</p>
</blockquote>
</li>
<li>
<p>ServerSocket 类</p>
<p>表示服务器程序的类： java.net.ServerSocket</p>
<blockquote>
<p>构造方法： ServerSocket (int port)： 传递端口号</p>
</blockquote>
<blockquote>
<p>必须要获得客户端的套接字对象 Socket：Socket accept ()</p>
</blockquote>
</li>
<li>
<p>TCP 图片上传示例</p>
<p>客户端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Socket套接字连接服务器</span></span><br><span class="line"><span class="comment"> * 通过Socket获取字节输出流,写图片</span></span><br><span class="line"><span class="comment"> * 使用自己的流对象,读取图片数据源(FileInputStream、缓冲流）</span></span><br><span class="line"><span class="comment"> * 读取图片,使用字节输出流,将图片写到服务器（采用字节数组进行缓冲）</span></span><br><span class="line"><span class="comment"> * 通过Socket套接字获取字节输入流，读取服务器发回来的上传成功</span></span><br><span class="line"><span class="comment"> * 关闭资源</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TCPClient</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        Socket socket = <span class="keyword">new</span> Socket(<span class="string">&quot;127.0.0.1&quot;</span>,<span class="number">8000</span>);</span><br><span class="line">        <span class="comment">//获取字节输出流，将图片写到服务器</span></span><br><span class="line">        OutputStream out = socket.getOutputStream();</span><br><span class="line">        <span class="comment">//创建字节输入流，读取本机上的数据源图片</span></span><br><span class="line">        FileInputStream fis = <span class="keyword">new</span> FileInputStream(<span class="string">&quot;D:\\test.jpg&quot;</span>);</span><br><span class="line">        <span class="comment">//开始读写字节数组</span></span><br><span class="line">        <span class="keyword">int</span> len = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="keyword">while</span>((len = fis.read(bytes)) != -<span class="number">1</span>)&#123;</span><br><span class="line">            out.write(bytes,<span class="number">0</span>,len);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//给服务器写终止序列,向服务端写入一个结束标志</span></span><br><span class="line">        socket.shutdownOutput();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取字节输入流，读取服务器的&quot;上传成功&quot;</span></span><br><span class="line">        InputStream in = socket.getInputStream();</span><br><span class="line"></span><br><span class="line">        len = in.read(bytes); <span class="comment">//复用byte数组</span></span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(bytes,<span class="number">0</span>,len));</span><br><span class="line"></span><br><span class="line">        fis.close();</span><br><span class="line">        socket.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>服务端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ServerSocket套接字对象,监听端口8000</span></span><br><span class="line"><span class="comment"> * 方法accept()获取客户端的连接对象</span></span><br><span class="line"><span class="comment"> * 客户端连接对象获取字节输入流,读取客户端发送图片</span></span><br><span class="line"><span class="comment"> * 创建File对象，绑定上传文件夹（判断文件夹存在，不存在，创建文件夹）</span></span><br><span class="line"><span class="comment"> * 创建字节输出流，数据目的File对象所在文件夹</span></span><br><span class="line"><span class="comment"> * 字节流读取图片，字节流将图片写入到目的文件夹中</span></span><br><span class="line"><span class="comment"> * 将上传成功会写客户端</span></span><br><span class="line"><span class="comment"> * 关闭资源</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TCPServer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        ServerSocket server = <span class="keyword">new</span> ServerSocket(<span class="number">8000</span>);</span><br><span class="line">        Socket socket = server.accept();</span><br><span class="line">        <span class="comment">//通过客户端连接对象,获取字节输入流,读取客户端图片</span></span><br><span class="line">        InputStream in = socket.getInputStream();</span><br><span class="line">        <span class="comment">//将目的文件夹封装到File对象</span></span><br><span class="line">        File upload = <span class="keyword">new</span> File(<span class="string">&quot;E:\\upload&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span>(! upload.exists())&#123;</span><br><span class="line">            upload.mkdirs();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//防止文件同名被覆盖,重新定义文件名字</span></span><br><span class="line">        <span class="comment">//规则:  域名+当前毫秒值+6位随机数</span></span><br><span class="line">        String filename=<span class="string">&quot;wangdao&quot;</span>+System.currentTimeMillis()+<span class="keyword">new</span> Random().nextInt(<span class="number">999999</span>)+<span class="string">&quot;.jpg&quot;</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建字节输出流,将图片写入到目的文件夹中</span></span><br><span class="line">        FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(upload+File.separator+filename);</span><br><span class="line">        <span class="comment">//读写字节数组</span></span><br><span class="line">        <span class="keyword">byte</span>[] bytes = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="keyword">int</span> len = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span>((len = in.read(bytes)) != -<span class="number">1</span>)&#123;</span><br><span class="line">            fos.write(bytes,<span class="number">0</span>,len);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过客户端连接对象获取字节输出流</span></span><br><span class="line">        <span class="comment">//将&quot;上传成功&quot;写回客户端</span></span><br><span class="line">        socket.getOutputStream().write(<span class="string">&quot;上传成功！&quot;</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        fos.close();</span><br><span class="line">        socket.close();</span><br><span class="line">        server.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-udp通信"><a class="markdownIt-Anchor" href="#4-udp通信">#</a> 4、UDP 通信</h4>
<ol>
<li>
<p>实现封装数据的类 java.net.DatagramPacket 将数据包装或拆分，java.net.DatagramSocket 将数据包发送或接受</p>
<blockquote>
<p>DatagramPacket 构造方法：DatagramPacket ()：参数字节数组，发送多少，IP 地址，端口号<br>
 DatagramSocket 构造方法：DatagramSocket ()：空参数<br>
方法: send () ：参数数据包</p>
</blockquote>
</li>
<li>
<p>示例</p>
<p>发送端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 创建 DatagramPacket 对象,封装数据, 接收的地址和端口</span></span><br><span class="line"><span class="comment"> * 创建 DatagramSocket 对象</span></span><br><span class="line"><span class="comment"> * 调用 DatagramSocket 类方法 send ，发送数据包</span></span><br><span class="line"><span class="comment"> * 关闭资源</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UDPSend</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException</span>&#123;</span><br><span class="line">        <span class="comment">//创建数据包对象,封装要发送的数据,接收端IP,端口 </span></span><br><span class="line">        <span class="keyword">byte</span>[] date = <span class="string">&quot;你好UDP&quot;</span>.getBytes();</span><br><span class="line">        <span class="comment">//创建InetAddress对象,封装自己的IP地址 </span></span><br><span class="line">        InetAddress inet = InetAddress.getByName(<span class="string">&quot;127.0.0.1&quot;</span>);</span><br><span class="line">        DatagramPacket dp = <span class="keyword">new</span> DatagramPacket(date, date.length, inet,<span class="number">6000</span>);</span><br><span class="line">        <span class="comment">//创建DatagramSocket对象,数据包的发送和接收对象 </span></span><br><span class="line">        DatagramSocket ds = <span class="keyword">new</span> DatagramSocket();</span><br><span class="line">        <span class="comment">//调用ds对象的方法send,发送数据包 </span></span><br><span class="line">        ds.send(dp);</span><br><span class="line">        <span class="comment">//关闭资源 </span></span><br><span class="line">        ds.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接收端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 创建 DatagramSocket 对象，绑定端口号，要和发送端端口号一致</span></span><br><span class="line"><span class="comment"> * 创建字节数组，接收发来的数据</span></span><br><span class="line"><span class="comment"> * 创建数据包对象 DatagramPacket</span></span><br><span class="line"><span class="comment"> * 调用 DatagramSocket 对象方法，receive(DatagramPacket dp)接收数据，数据放在数据包中</span></span><br><span class="line"><span class="comment"> * 拆包：</span></span><br><span class="line"><span class="comment"> * 关闭资源</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UDPReceive</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span><span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//创建数据包传输对象DatagramSocket 绑定端口号</span></span><br><span class="line">        DatagramSocket ds = <span class="keyword">new</span> DatagramSocket(<span class="number">6000</span>);</span><br><span class="line">        <span class="comment">//创建字节数组</span></span><br><span class="line">        <span class="keyword">byte</span>[] data = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="comment">//创建数据包对象,传递字节数组</span></span><br><span class="line">        DatagramPacket dp = <span class="keyword">new</span> DatagramPacket(data, data.length);</span><br><span class="line">        <span class="comment">//调用ds对象的方法receive传递数据包</span></span><br><span class="line">        ds.receive(dp);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取发送端的IP地址对象</span></span><br><span class="line">        String ip=dp.getAddress().getHostAddress();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取发送的端口号</span></span><br><span class="line">        <span class="keyword">int</span> port = dp.getPort();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取接收到的字节个数</span></span><br><span class="line">        <span class="keyword">int</span> length = dp.getLength();</span><br><span class="line">        System.out.println(ip+<span class="string">&quot; &quot;</span>+port+<span class="string">&quot;:&quot;</span>+<span class="keyword">new</span> String(data,<span class="number">0</span>,length));</span><br><span class="line">        ds.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ol>

  </div>

   <footer>

    <div class="meta">
  <span class="item">
    <span class="icon">
      <i class="ic i-calendar-check"></i>
    </span>
    <span class="text">Edited on</span>
    <time title="Modified: 2020-12-23 23:31:51" itemprop="dateModified" datetime="2020-12-23T23:31:51+08:00">2020-12-23</time>
  </span>
</div>

      
<div class="reward">
  <button><i class="ic i-heartbeat"></i> Donate</button>
  <p>Give me a cup of [coffee]~(￣▽￣)~*</p>
  <div id="qr">
      
      <div>
        <img data-src="/lostyu/images/wechatpay.png" alt="Eden的个人世界 WeChat Pay">
        <p>WeChat Pay</p>
      </div>
      
      <div>
        <img data-src="/lostyu/images/alipay.png" alt="Eden的个人世界 Alipay">
        <p>Alipay</p>
      </div>
      
      <div>
        <img data-src="/lostyu/images/paypal.png" alt="Eden的个人世界 PayPal">
        <p>PayPal</p>
      </div>
  </div>
</div>

      

<div id="copyright">
<ul>
  <li class="author">
    <strong>Post author:  </strong>Eden的个人世界 <i class="ic i-at"><em>@</em></i>Eden
  </li>
  <li class="link">
    <strong>Post link: </strong>
    <a href="https://luhongdeng.gitee.io/2020/12/23/Java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" title="Java网络编程">https://luhongdeng.gitee.io/2020/12/23/Java网络编程/</a>
  </li>
  <li class="license">
    <strong>Copyright Notice:  </strong>All articles in this blog are licensed under <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC9kZWVkLnpo"><i class="ic i-creative-commons"><em>(CC)</em></i>BY-NC-SA</span> unless stating additionally.
  </li>
</ul>
</div>

  </footer>

</article>

  </div>
  

<div class="post-nav">
    <div class="item left">
      

  <a href="/lostyu/2020/12/23/io%E6%B5%81%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C/" itemprop="url" rel="prev" data-background-image="https:&#x2F;&#x2F;tva4.sinaimg.cn&#x2F;mw690&#x2F;6833939bly1gipexoj0moj20zk0m8kgu.jpg" title="io流常用操作..o">
  <span class="type">Previous Post</span>
  <span class="category"><i class="ic i-flag"></i> </span>
  <h3>io流常用操作..o</h3>
  </a>

    </div>
    <div class="item right">
    </div>
</div>

  
  <div class="wrap" id="comments"></div>


        </div>
        <div id="sidebar">
          

<div class="inner">

  <div class="panels">
    <div class="inner">
      <div class="contents panel pjax" data-title="Contents">
          <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80-%E4%BB%80%E4%B9%88%E6%98%AF%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text"> 一、什么是网络编程</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-7%E5%B1%82%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B-osi"><span class="toc-number">1.1.</span> <span class="toc-text"> 1、7 层网络模型 - OSI</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B-%E5%AF%B9%E5%BA%94%E5%85%B3%E7%B3%BB"><span class="toc-number">1.2.</span> <span class="toc-text"> 2、网络模型 - 对应关系</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-socket%E4%B8%8Etcp-udp"><span class="toc-number">1.3.</span> <span class="toc-text"> 3、Socket 与 TCP、UDP</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-tcp%E9%80%9A%E4%BF%A1"><span class="toc-number">1.4.</span> <span class="toc-text"> 4、TCP 通信</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-udp%E9%80%9A%E4%BF%A1"><span class="toc-number">1.5.</span> <span class="toc-text"> 4、UDP 通信</span></a></li></ol></li></ol>
      </div>
      <div class="related panel pjax" data-title="Related">
      </div>
      <div class="overview panel" data-title="Overview">
        <div class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="image" itemprop="image" alt="Eden的个人世界"
      data-src="/lostyu/images/avatar.jpg">
  <p class="name" itemprop="name">Eden的个人世界</p>
  <div class="description" itemprop="description"></div>
</div>

<nav class="state">
    <div class="item posts">
      <a href="/lostyu/archives/">
        <span class="count">5</span>
        <span class="name">posts</span>
      </a>
    </div>
</nav>

<div class="social">
      <span class="exturl item github" data-url="aHR0cHM6Ly9naXRodWIuY29tL3lvdXJuYW1l" title="https:&#x2F;&#x2F;github.com&#x2F;yourname"><i class="ic i-github"></i></span>
      <span class="exturl item twitter" data-url="aHR0cHM6Ly90d2l0dGVyLmNvbS95b3VybmFtZQ==" title="https:&#x2F;&#x2F;twitter.com&#x2F;yourname"><i class="ic i-twitter"></i></span>
      <span class="exturl item zhihu" data-url="aHR0cHM6Ly93d3cuemhpaHUuY29tL3Blb3BsZS95b3VybmFtZQ==" title="https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;yourname"><i class="ic i-zhihu"></i></span>
      <span class="exturl item music" data-url="aHR0cHM6Ly9tdXNpYy4xNjMuY29tLyMvdXNlci9ob21lP2lkPXlvdXJpZA==" title="https:&#x2F;&#x2F;music.163.com&#x2F;#&#x2F;user&#x2F;home?id&#x3D;yourid"><i class="ic i-cloud-music"></i></span>
      <span class="exturl item weibo" data-url="aHR0cHM6Ly93ZWliby5jb20veW91cm5hbWU=" title="https:&#x2F;&#x2F;weibo.com&#x2F;yourname"><i class="ic i-weibo"></i></span>
      <span class="exturl item about" data-url="aHR0cHM6Ly9hYm91dC5tZS95b3VybmFtZQ==" title="https:&#x2F;&#x2F;about.me&#x2F;yourname"><i class="ic i-address-card"></i></span>
</div>

<ul class="menu">
  
    
  <li class="item">
    <a href="/lostyu/" rel="section"><i class="ic i-home"></i>Home</a>
  </li>


</ul>

      </div>
    </div>
  </div>

  <ul id="quick">
    <li class="prev pjax">
    </li>
    <li class="up"><i class="ic i-arrow-up"></i></li>
    <li class="down"><i class="ic i-arrow-down"></i></li>
    <li class="next pjax">
    </li>
    <li class="percent"></li>
  </ul>
</div>


        </div>
        <div class="dimmer"></div>
      </div>
    </main>
    <footer id="footer">
      <div class="inner">
        <div class="widgets">
          
<div class="rpost pjax">
  <h2>Random Posts</h2>
  <ul>
      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/lostyu/2020/12/23/hello-world/" title="Hello World">Hello World</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/lostyu/2020/12/23/io%E6%B5%81%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C/" title="io流常用操作..o">io流常用操作..o</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/lostyu/2020/12/23/dubbo/" title="dubbo">dubbo</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/lostyu/2020/12/23/Java%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" title="Java网络编程">Java网络编程</a></span>
  </li>

      
  <li class="item">
    
<div class="breadcrumb">
</div>

    <span><a href="/lostyu/2020/12/23/zookeeper/" title="zookeeper">zookeeper</a></span>
  </li>

  </ul>
</div>
<div>
  <h2>Recent Comments</h2>
  <ul class="leancloud-recent-comment"></ul>
</div>

        </div>
        <div class="status">
  <div class="copyright">
    
    &copy; 2010 – 
    <span itemprop="copyrightYear">2020</span>
    <span class="with-love">
      <i class="ic i-sakura rotate"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Eden的个人世界 @ 我的金子，只给千寻</span>
  </div>
  <div class="powered-by">
    Powered by <span class="exturl" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & Theme.<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FtZWhpbWUvaGV4by10aGVtZS1zaG9rYQ==">Shoka</span>
  </div>
</div>

      </div>
    </footer>
  </div>
<script data-config type="text/javascript">
  var LOCAL = {
    path: '2020/12/23/Java网络编程/',
    favicon: {
      show: "（●´3｀●）Goooood",
      hide: "(´Д｀)Booooom"
    },
    search : {
      placeholder: "Search for Posts",
      empty: "We didn't find any results for the search: ${query}",
      stats: "${hits} results found in ${time} ms"
    },
    valine: true,fancybox: true,copyright: 'Copied to clipboard successfully! <br> All articles in this blog are licensed under <i class="ic i-creative-commons"></i>BY-NC-SA.',
    ignores : [
      function(uri) {
        return uri.includes('#');
      },
      function(uri) {
        return new RegExp(LOCAL.path+"$").test(uri);
      }
    ]
  };
</script>

<script src="https://cdn.polyfill.io/v2/polyfill.js"></script>

<script src="//cdn.jsdelivr.net/combine/npm/pace-js@1.0.2/pace.min.js,npm/pjax@0.2.8/pjax.min.js,npm/whatwg-fetch@3.4.0/dist/fetch.umd.min.js,npm/animejs@3.2.0/lib/anime.min.js,npm/algoliasearch@4/dist/algoliasearch-lite.umd.js,npm/instantsearch.js@4/dist/instantsearch.production.min.js,npm/lozad@1/dist/lozad.min.js,npm/quicklink@2/dist/quicklink.umd.js"></script>

<script src="/lostyu/js/app.js?v=0.2.5"></script>




</body>
</html>
